import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionService extends GetxService {

  Future<bool> checkAndRequestCorePermissions() async {
    // --- 1. 通知权限 (Android 13+) ---
    PermissionStatus notificationStatus = await Permission.notification.status;
    
    // 只有在权限未被授予时才发起请求流程
    if (!notificationStatus.isGranted) {
      bool? userAgreed = await showPermissionDialog(
        title: '通知权限',
        content: '为在手机顶部状态栏显示服务运行状态，APP需要获取通知权限。',
      );

      if (userAgreed == true) {
        // 发起请求
        notificationStatus = await Permission.notification.request();

        // 【核心优化】请求后再次检查状态
        // 如果权限被永久拒绝(isPermanentlyDenied)，则引导用户去设置
        if (notificationStatus.isPermanentlyDenied || notificationStatus.isDenied) {
          await showGotoSettingsDialog(
            title: '需要通知权限',
            content: '您已拒绝通知权限。请在应用设置中手动开启，否则无法在状态栏看到服务运行状态。',
          );
        }
      } else {
        showPermissionDeniedDialog('通知权限未开启，您将无法在状态栏看到服务运行状态。');
      }
    }

    // --- 2. 电池优化权限 ---
    // (这部分的逻辑保持不变，因为电池优化权限通常不会被“永久拒绝”)
    PermissionStatus batteryStatus = await Permission.ignoreBatteryOptimizations.status;
    if (!batteryStatus.isGranted) {
      bool? userAgreed = await showPermissionDialog(
        title: '电池优化权限',
        content: '为确保抢单服务在后台稳定运行不被系统“杀死”，需要您将APP加入电池优化白名单。',
      );
      if (userAgreed == true) {
        await Permission.ignoreBatteryOptimizations.request();
      } else {
        showPermissionDeniedDialog('电池优化权限未开启，后台服务可能随时被系统关闭。');
        return false;
      }
    }
    
    batteryStatus = await Permission.ignoreBatteryOptimizations.status;
    if (!batteryStatus.isGranted) {
      return false;
    }
    
    return true;
  }

  // 【新增】一个专门用于引导用户跳转到系统设置的对话框
  Future<void> showGotoSettingsDialog({
    required String title,
    required String content,
  }) {
    return Get.dialog(
      AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back(); // 先关闭对话框
              AppSettings.openAppSettings(type: AppSettingsType.notification); // 跳转到通知设置
            },
            child: const Text('去设置'),
          ),
        ],
      ),
       barrierDismissible: false,
    );
  }

  // (requestAccessibilityPermission 和其他对话框方法保持不变)
  Future<void> requestAccessibilityPermission() async {
      bool? userAgreed = await showPermissionDialog(
        title: '无障碍服务权限',
        content: '这是实现自动抢单最核心的权限，APP需要通过它来监测订单弹窗并模拟点击。请在跳转后的页面中找到[抢单助手]并开启它。',
        confirmText: '去开启',
      );

      if (userAgreed == true) {
        await AppSettings.openAppSettings(type: AppSettingsType.accessibility);
      }
  }

  Future<bool?> showPermissionDialog({
    required String title,
    required String content,
    String confirmText = '好的',
    String cancelText = '取消',
  }) {
    return Get.dialog<bool>(
      AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text(cancelText),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            child: Text(confirmText),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

  Future<void> showPermissionDeniedDialog(String content) {
    return Get.dialog(
      AlertDialog(
        title: const Text('权限提示'),
        content: Text(content),
        actions: [
          ElevatedButton(
            onPressed: () => Get.back(),
            child: const Text('我知道了'),
          ),
        ],
      ),
    );
  }
}